package org.yhx.learning.jukebox;/*
 * Copyright (C), 2024, 17081794
 * FileName:
 * Author:   17081794
 * Date:     2024/9/6 17:18
 * Description: //模块目的、功能描述
 * History: //修改记录
 * &lt;author&gt;      &lt;time&gt;      &lt;version&gt;    &lt;desc&gt;
 * 修改人姓名             修改时间            版本号                  描述
 */

import io.vertx.core.AbstractVerticle;
import io.vertx.core.AsyncResult;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.net.NetSocket;
import io.vertx.core.parsetools.RecordParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.Socket;

public class NetControl extends AbstractVerticle {

    private static final Logger LOGGER = LoggerFactory.getLogger(NetControl.class);


    @Override
    public void start() throws Exception {

        vertx.createNetServer().connectHandler(this::handleSocket).listen(3000);
    }

    private void handleSocket(NetSocket socket) {
        LOGGER.info("New connection");
        RecordParser.newDelimited("\n", socket)
                .endHandler(v -> socket.end())
                .handler(buffer -> handleBuffer(socket, buffer));

    }

    private void handleBuffer(NetSocket socket, Buffer buffer) {

        String command = buffer.toString();

        switch (command) {

            case "/list":
                listCommand(socket);
                break;
            case "/play":
                vertx.eventBus().send("jukebox.play", "");
                break;
            case "/pause":
                vertx.eventBus().send("jukebox.pause", "");
                break;
            default:
                if (command.startsWith("/schedule ")) {
                    schedule(command);
                } else {
                    socket.write("Unknown command\n");
                }

        }
    }

    private void listCommand(NetSocket socket) {

        vertx.eventBus().<JsonArray>request("jukebox.list", "", ar -> {

            if (ar.succeeded()) {
                socket.write(ar.result().body().toString());
            } else {
                LOGGER.error("消费jukebox.list 发生异常", ar.cause());
            }
        });

        vertx.fileSystem().readDir("tracks", ".*mp3$", ar -> {

            if (ar.succeeded()) {
                socket.write(ar.result().toString());
            } else {
                LOGGER.error("获取MP3文件列表异常");
            }
        });
    }


    private void schedule(String command) {

        String substring = command.substring(10);
        vertx.eventBus().request("jukebox.schedule", JsonObject.of("file", substring));
    }
}
